package com.enid.rongtalkdemo;

import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import java.util.Locale;

import io.rong.callkit.RongCallAction;
import io.rong.callkit.RongCallKit;
import io.rong.callkit.RongVoIPIntent;
import io.rong.calllib.RongCallClient;
import io.rong.calllib.RongCallCommon;
import io.rong.calllib.RongCallSession;
import io.rong.imkit.RongIM;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Conversation;
import io.rong.imlib.model.UserInfo;

public class MainActivity extends AppCompatActivity {
    private String userPhoto1 = "http://img0.imgtn.bdimg.com/it/u=737277182,2730582748&fm=26&gp=0.jpg";
    private String userPhoto2 = "http://img1.imgtn.bdimg.com/it/u=2561011807,290788206&fm=26&gp=0.jpg";
    private String userPhoto = "";
    private String test1Token = "DCjmQjHHM2rzxZL8CcNg2277uPnsmQMGGnYPWSr3Z2sMNN1BYaspCf4KlNud028ua5xEzdAtQj42lu5puVqUhA==";
    private String test2Token = "gBx8pGtBB5mqcMclLJbpiQKUfvEtVwUqQ5/khPsdQetKoluW+BlX/BPmug3W2JceLydj9tPQEOlx7I/kqn934w==";
    private String userName1 = "测试用户1";
    private String userName2 = "测试用户2";

    private EditText targetUserIdText;
    private String token;
    private String targetName;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        TextView loginUserText = findViewById(R.id.loginUserText);
        targetUserIdText = findViewById(R.id.userIdText);

        String name = PreferenceUtil.getString(this, ConstantUtil.USER_NAME);
        String id = PreferenceUtil.getString(this, ConstantUtil.USER_ID);
        token = PreferenceUtil.getString(this, ConstantUtil.RONGYUN_USER_TOKEN);
        loginUserText.setText("loginUser: " + name + "\nuserId:" + id + "\ntoken: " + token);
        if (id.equals("test1")) {
            targetUserIdText.setText("test2");
        } else {
            targetUserIdText.setText("test1");
        }
    }

    private void initTargetUserInfoTest() {
        String targetImage = "";
        targetName = "";
        String targetId = targetUserIdText.getText().toString();
        if (targetId.equals("test1")) {
            targetImage = userPhoto1;
            targetName = userName1;
        } else {
            targetImage = userPhoto2;
            targetName = userName2;
        }
//        RongIM.getInstance().refreshUserInfoCache(new UserInfo(targetId, "", Uri.parse("")));
    }

    public void onChat(final View view) {
        initTargetUserInfoTest();
        startChat(view);
    }

    public void onVideo(View view) {
        initTargetUserInfoTest();
        String displayName = targetUserIdText.getText().toString();
        startVideoCall(this, displayName);
    }

    public void onPhone(View view) {
        initTargetUserInfoTest();
        String displayName = targetUserIdText.getText().toString();
        startAudioCall(this, displayName);
    }

    public void onList(View view) {
//        initTargetUserInfoTest();
        ConservationListActivity.actionStart(MainActivity.this);
    }

    public void onExit(View view) {
        PreferenceUtil.putString(this, ConstantUtil.RONGYUN_USER_TOKEN, "");
        finish();
    }

    public void startChat(View view) {
        String targetUserId = targetUserIdText.getText().toString();
        RongIM.getInstance().startPrivateChat(this, targetUserId, targetName);
    }

    private void startVideoCall(Context context, String targetId) {
        RongCallKit.startSingleCall(context, targetId, RongCallKit.CallMediaType.CALL_MEDIA_TYPE_VIDEO);
    }

    private void startAudioCall(Context context, String targetId) {
        RongCallKit.startSingleCall(context, targetId, RongCallKit.CallMediaType.CALL_MEDIA_TYPE_AUDIO);
    }

    //CallKit start 2
    public void startVoice(View view) {
        String targetUserId = targetUserIdText.getText().toString();
        RongCallSession profile = RongCallClient.getInstance().getCallSession();
        if (profile != null && profile.getActiveTime() > 0) {
            Toast.makeText(this,
                    profile.getMediaType() == RongCallCommon.CallMediaType.AUDIO ?
                            getString(io.rong.callkit.R.string.rc_voip_call_audio_start_fail) :
                            getString(io.rong.callkit.R.string.rc_voip_call_video_start_fail),
                    Toast.LENGTH_SHORT)
                    .show();
            return;
        }
        ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = cm.getActiveNetworkInfo();
        if (networkInfo == null || !networkInfo.isConnected() || !networkInfo.isAvailable()) {
            Toast.makeText(this, getString(io.rong.callkit.R.string.rc_voip_call_network_error), Toast.LENGTH_SHORT).show();
            return;
        }

        Intent intent = new Intent(RongVoIPIntent.RONG_INTENT_ACTION_VOIP_SINGLEAUDIO);
        intent.putExtra("conversationType", Conversation.ConversationType.PRIVATE.getName().toLowerCase(Locale.US));
        intent.putExtra("targetId", targetUserId);
        intent.putExtra("callAction", RongCallAction.ACTION_OUTGOING_CALL.getName());
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setPackage(getPackageName());
        getApplicationContext().startActivity(intent);
    }

    public void startVideo(View view) {
        String targetUserId = targetUserIdText.getText().toString();
        RongCallSession profile = RongCallClient.getInstance().getCallSession();
        if (profile != null && profile.getActiveTime() > 0) {
            Toast.makeText(this,
                    profile.getMediaType() == RongCallCommon.CallMediaType.AUDIO ?
                            getString(io.rong.callkit.R.string.rc_voip_call_audio_start_fail) :
                            getString(io.rong.callkit.R.string.rc_voip_call_video_start_fail),
                    Toast.LENGTH_SHORT)
                    .show();
            return;
        }
        ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = cm.getActiveNetworkInfo();
        if (networkInfo == null || !networkInfo.isConnected() || !networkInfo.isAvailable()) {
            Toast.makeText(this, getString(io.rong.callkit.R.string.rc_voip_call_network_error), Toast.LENGTH_SHORT).show();
            return;
        }
        Intent intent = new Intent(RongVoIPIntent.RONG_INTENT_ACTION_VOIP_SINGLEVIDEO);
        intent.putExtra("conversationType", Conversation.ConversationType.PRIVATE.getName().toLowerCase(Locale.US));
        intent.putExtra("targetId", targetUserId);
        intent.putExtra("callAction", RongCallAction.ACTION_OUTGOING_CALL.getName());
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setPackage(getPackageName());
        getApplicationContext().startActivity(intent);
    }


    public static String getCurProcessName(Context context) {
        int pid = android.os.Process.myPid();
        ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        for (ActivityManager.RunningAppProcessInfo appProcess : activityManager.getRunningAppProcesses()) {
            if (appProcess.pid == pid) {
                return appProcess.processName;
            }
        }
        return "";
    }
}
